<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<%
    String path = request.getContextPath();
%>
	<div id="page-wrapper">
        <div id="page-inner">
            <div class="row">
                <div class="col-md-12">
                    <!-- Advanced Tables -->
                    <div class="panel panel-default">
                        <div class="panel-heading">检查站信息列表</div>
                        <div class="panel-body">
                            <form class="form-horizontal">
                                <div class="form-group">
                                    <label for="organizationName" class="col-md-2 control-label">检查站名称</label>
                                    <div class="col-md-2">
                                        <input type="text" class="form-control" id="organizationName"
                                               placeholder="检查站名称">
                                    </div>
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    <a type="search" onclick="load(1)" class="btn btn-primary">搜索</a>
                                </div>
                            </form>

                            <div id="toolbar" class="btn-group">
                                <button id="btn_add" type="button" class="btn btn-default" data-toggle="modal"
                                        data-target="#myModal">
                                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
                                </button>
                            </div>
							<div id="toolbar" class="btn-group">
                                <button id="btn_add" type="button" class="btn btn-default" data-toggle="modal"
                                        data-target="#myModal2">
                                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>导入检查站
                                </button>
                            </div>
                            <div style="height:20px"></div>
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered table-hover"
                                       id="dataTables-example">
                                    <thead>
                                    <tr>
                                        <th>序号</th>
                                        <th>检查站名称</th>
                                        <th>经度</th>
                                        <th>纬度</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody id="tbody">
                                    </tbody>
                                </table>
                                <div style="float:right" id="page" class="tr"></div>
                            </div>

                        </div>
                    </div>
                    <!--End Advanced Tables -->
                </div>
            </div>
        </div>
    </div>
<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                </h4>
            </div>
            <div class="modal-body">
                <form action="" id="tripinfo">
                    <div class="form-body pal">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="" class="control-label">检查站名称</label>
                                    <div class="">
                                        <input id="organizationname" type="text" name="organizationName"
                                               class="form-control"></div>
                                    <input id="organizationInfoId" name="organizationInfoId" style="display: none">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="" class="control-label">经度</label>
                                    <div class="">
                                        <input id="longitude" type="text" name="longitude"
                                               class="form-control"></div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="" class="control-label">纬度</label>
                                    <div class="">
                                        <input id="latitude" type="text" name="latitude"
                                               class="form-control"></div>
                                </div>
                            </div>

                        </div>
                    </div>
                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
                <button id="tripinfoButton" type="button" class="btn btn-primary">提交
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div>
</div><!-- /.modal -->


<!-- 模态框（Modal） -->
<div class="modal fade bs-example-modal-lg" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">导入检查站
                </h4>
            </div>
            <div class="modal-body">
                <form id="excelForm" class="form-horizontal"
					action="<%=path%>/importOrganization" method="post"
					enctype="multipart/form-data">
					<div class="form-group">
						<div class="col-md-1"></div>
						<div class="col-md-2">
							<button type="button" class="btn btn-default"
								onclick='location.href = "<%=path%>/template/organizationTemplate.xlsx"'>下载模板</button>
						</div>
						<div class="col-md-5">
							<input type="text" id="fileName" name="fileName"
								class="form-control" readonly="readonly"
								onclick="$('#excelFile').click();" placeholder="选择导入的Excel" /> <input
								type="file" id="excelFile" name="excelFile" style="display: none;"
								onchange="$('#fileName').val(this.value)" />
						</div>
						<div class="col-md-2">
							<button type="button" id="importButton" class="btn btn-default" onclick="organizationImport()">导入模板</button>
						</div>
						<div class="col-md-12">
							<div class="panel-body table-responsive">
								<table class="table table-bordered" style="font-size: 5px;">
									<thead>
										<tr>
											<th>行号</th>
											<th>检查站名称</th>
											<th>经度</th>
											<th>纬度</th>
											<th>导入结果</th>
										</tr>
									</thead>
									<tbody id="importTB">
										
									</tbody>
								</table>
							</div>
						</div>
					</div>
				</form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div>
</div><!-- /.modal -->

<script>
    $(document).ready(function () {
        load(1);
    });
    
    function valContent(){
        return $('#tripinfo').validate({
            rules: {
            	organizationName: {
                    required: true
                },
                longitude: {
                	isLongitude: true,
                    required: true
                },
                latitude: {
                	isLatitude: true,
                	required: true
                }
            },
            highlight: function(element) {
                $(element).closest('.form-group').removeClass('success').addClass('error');
            },
            success: function(element) {
                element.text('OK!').addClass('valid')
                    .closest('.form-group').removeClass('error').addClass('success');
            }
        }).form();
    }
    
    //添加修改
    $("#tripinfoButton").on('click', function (e) {
    	if(valContent()){
    		var organizationName = $("#organizationname").val();
            var organizationInfoId = $("#organizationInfoId").val();
            var longitude = $("#longitude").val();
            var latitude = $("#latitude").val();
            $.ajax({
                url: "<%=path%>/saveOrUpdateOrganizationInfo",
                dataType: "json",
                type: 'post',
                data: {
                    "organizationInfoId": organizationInfoId,
                    "organizationName": organizationName,
                    "longitude": longitude,
                    "latitude": latitude
                },
                success: function (result) {
                    if (result.state == 1) {
                        swal({
                            title: result.msg,
                            type: "success",
                            confirmButtonText: '确认',
                            confirmButtonColor: '#5bc0de'
                        }, function () {
                            load(1);
                            $('.close').click();
                        })
                    } else {
                        swal(result.msg, "操作失败", "warning");
                    }
                },
                error: function () {
                    swal("操作失败", "warning");
                }
            })
    	}
    })


    $('#myModal').on('hidden.bs.modal', function () {
        $("#tripinfo")[0].reset();
        $("label.error").remove();
    })
	$('#myModal2').on('hidden.bs.modal', function () {
        $("#excelForm")[0].reset();
        $('#importTB').html('');
    })
    $('#myModal').on('show.bs.modal', function () {
        if ($("#tripinfo #organizationName").val() == "") {
            $("#myModal #myModalLabel").text("添加检查站信息")
            $("#myModal #managerButton").text("提交")
        } else {
            $("#myModal #myModalLabel").text("修改检查站信息")
            $("#myModal #managerButton").text("确定")
        }
    })


    //回显
    function editTripInfo(id) {
        $.ajax({
            url: "<%=path%>/viewOrganizationInfo",
            dataType: "json",
            type: 'post',
            data: {
                "key": id,
            },
            success: function (result) {
                $("#tripinfo #organizationInfoId").val(result.organizationInfoId);
                $("#tripinfo #organizationname").val(result.organizationName);
                $("#tripinfo #longitude").val(result.longitude);
                $("#tripinfo #latitude").val(result.latitude);
                $("#myModal").modal('toggle')
            },
        })

    }

    //删除
    function deleteTripInfo(id) {
        swal({
                title: "确定删除吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定删除！",
                cancelButtonText: "取消删除！",
                closeOnConfirm: false,
                closeOnCancel: true
            },
            function (isConfirm) {
                if (isConfirm) {
                    $.ajax({
                        url: "<%=path%>/delTripinfo",
                        type: 'post',
                        data: {"key": id},
                        dataType: 'json',
                        success: function (data) {
                            if (data.num == 1) {
                                swal({
                                        title: "删除成功",
                                        type: "success",
                                        confirmButtonText: '确认',
                                        confirmButtonColor: '#5bc0de',
                                    },
                                    function () {
                                        load(1);
                                    });
                            } else {
                                swal({
                                        title: "删除失败",
                                        type: "error",
                                        confirmButtonText: '确认',
                                        confirmButtonColor: '#5bc0de',
                                    },
                                    function () {
                                        load(1);
                                    });
                            }
                        },
                        error: function () {
                            swal({
                                    title: "删除失败",
                                    type: "error",
                                    confirmButtonText: '确认',
                                    confirmButtonColor: '#5bc0de',
                                },
                                function () {
                                    load(1);
                                });
                        }
                    });
                }
            });

    }


    function load(curr) {

        var pageSize = 30; //每页出现的数量
        $.ajax({
            url: "<%=path%>/getOrganizationListList",
            timeout: 300000,
            dataType: "json",
            type: "post",
            data: {
                "curr": curr,
                "pageSize": pageSize,
                "organizationName": $("#organizationName").val(),
            },
            success: function (data) {
                var html = "";
                $.each(data.list, function (i, item) {
                    var id = item.organizationInfoId
                    var editid = "";
                    editid += "&nbsp;&nbsp;&nbsp;&nbsp;";
                    editid = "<a href='javascript:;' class='fa fa-edit' onclick=\"editTripInfo('" + id + "')\" title='编辑'>编辑</a>";
                    editid += "&nbsp;&nbsp;&nbsp;&nbsp;";
                    editid += "<a href='javascript:;' class='fa fa-trash-o' onclick=\"deleteTripInfo('" + id + "')\" title='删除'>删除</a>";

                    var n = i + 1;
                    html += " <tr> " +
                        " <td>" + n + "</td> " +
                        " <td>" + item.organizationName + "</td> " +
                        " <td>" + item.longitude + "</td> " +
                        " <td>" + item.latitude + "</td> " +
                        " <td>" + editid + "</td> " +

                        " </tr>";
                })
                $("#tbody").html(html);
                laypage({
                    cont: 'page', //容器。值支持id名、原生dom对象，jquery对象。【如该容器为】：<div id="page1"></div>
                    pages: Math.ceil(data.totalCount / 30),  //通过后台拿到的总页数
                    skin: "#49afcd",
                    curr: curr || 1, //当前页
                    jump: function (obj, first) { //触发分页后的回调
                        if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
                            curr = obj.curr;
                            load(curr);
                        }
                    }
                });

            }
        })
    }
    
    function organizationImport(){
    	var file = document.getElementById('excelFile');
        var fileName=file.value;    
        if(fileName=="")
        {
        	swal("提交失败", "请选择EXCEL文件", "error");
        	return false;
        }
    	while (fileName.indexOf("\\") != -1)
    	{
        fileName = fileName.slice(fileName.indexOf("\\") + 1);
    	}
        var ext = fileName.slice(fileName.indexOf(".")).toLowerCase();
        if(ext.indexOf("xls") == -1)
        {
        	swal("提交失败", "请上传格式为Excel的文件", "error");
        	return false;
        }
        $("#importButton").replaceWith("<img id='importImg' src='<%=path%>/assets/img/loading.gif' ></img>");
        $("#excelForm").ajaxSubmit(function(data) { 
        	if(data.errorMsg!=null&&data.errorMsg!=''){
        		swal({   
    				  title: "上传失败", 
    				  text: data.errorMsg, 
    				  type: "error",
    				},
    				function(){
    					$("#importImg").replaceWith('<button type="button" id="importButton" class="btn btn-info" onclick="organizationImport()">导入模板</button>');
    				});
        	}else{
        		var tbStr="";
        		for(var i=0;i<data.dataList.length;i++){
        			tbStr+="<tr>";
        			if (typeof(data.dataList[i].rowNo) == "undefined" ){
        				tbStr+="<td></td>";
        			}else{
        				tbStr+="<td>"+data.dataList[i].rowNo+"</td>";
        			}
    				if (typeof(data.dataList[i].col0) == "undefined" ){
    					tbStr+="<td></td>";
        			}else{
        				tbStr+="<td>"+data.dataList[i].col0+"</td>";
        			}
    				if (typeof(data.dataList[i].col1) == "undefined" ){
    					tbStr+="<td></td>";
    				}else{
    					tbStr+="<td>"+data.dataList[i].col1+"</td>";
    				}
    				if (typeof(data.dataList[i].col2) == "undefined" ){
    					tbStr+="<td></td>";
    				}else{
    					tbStr+="<td>"+data.dataList[i].col2+"</td>";
    				}
    				if (typeof(data.dataList[i].msg) == "undefined" ){
    					tbStr+="<td></td>";
    				}else{
    					tbStr+="<td>"+data.dataList[i].msg+"</td>";
    				}
        			tbStr+="</tr>";
        		}
        		$("#importTB").html(tbStr);
        		$("#importImg").replaceWith('<button type="button" id="importButton" class="btn btn-info" onclick="organizationImport()">导入模板</button>');
                load(1);
        	}
    	});
    }
</script>
